﻿Copper.DataStore = (function () {

    var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.moz_indexedDB;

    var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;

    var dbName = 'CopperDB';
    var taskStore = 'tasks';

    var copperDB = null;

    return {

        openDb: function () {
            var rq = indexedDB.open(dbName, 1);

            rq.onsuccess = function (e) {
                console.log('success');
            };

            rq.onupgradeneeded = function (e) {
            };

            rq.onerror = function (e) {
                console.log('error');
            };
        },

        initDb: function() {
            var request = indexedDB.open(dbName, 1);
            request.onsuccess = function (evt) {
                copperDB = request.result;
            };
 
            request.onerror = function (evt) {
                console.log("IndexedDB error: " + evt.target.errorCode);
            };
 
            request.onupgradeneeded = function (evt) {                   
                var objectStore = evt.currentTarget.result.createObjectStore(
                         "people", { keyPath: "id", autoIncrement: true });
 
                objectStore.createIndex("name", "name", { unique: false });
                objectStore.createIndex("email", "email", { unique: true });
 
                for (i in peopleData) {
                    objectStore.add(peopleData[i]);
                }
            };
        },

        loadTasks: function () {
            var transaction = copperDB.transaction(taskStore, IDBTransaction.READ_ONLY);
            var objectStore = transaction.objectStore(taskStore);

            objectStore.openCursor().onsuccess = function (evt) {
                var cursor = evt.result;

                if (cursor) { }
            };

            var request = objectStore.openCursor();
            request.onsuccess = function (evt) {
                var cursor = evt.target.result;
                if (cursor) {
                    output.textContent += "id: " + cursor.key +
                                " is " + cursor.value.name + " ";
                    cursor.continue();
                }
                else {
                    console.log("No more entries!");
                }
            };
        },

        addTask: function () { },

        updateTask: function(){},

        removeTask: function () { }

    };
})();